/**
 * name：用户权限分配
 * author: hj
 * time： 2020-01-13
 */
import React from 'react';
import IceContainer from '@icedesign/container';
import {Button, Checkbox, Collapse, Input, Message} from '@alifd/next';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import styles from './index.module.scss';
import responsive from '@/request'
import $http from '@/service/Services';

const axios = $http;
const Panel = Collapse.Panel;
let form;


/**
 * list
 */
class AuthorityEditComponents extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileId: "",
            userType: props.user, //user admin
            value: {},
            roleList: [],
            authList: [],
            id: "",
            tenantId: "",
            type: "",
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            },
            systemId: '', // 系统管理员Id
        };
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
        this.getAllMenuAuth = this.getAllMenuAuth.bind(this);
    }

    /**
     * 获取已授权的菜单列表
     */
    getInstanceRoleByRoleAndTenant = ()=>{
        const that = this;

        let roleId = this.state.id ? this.state.id : this.state.systemId;
        // if(this.state.id){
        axios.get(responsive.responsive.url + '/v1/auth/getRoleAuthByTenantAndRoleId/roleId/'+roleId+'/tenantId/' + this.state.tenantId)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    that.setState({
                        roleAuthList: data.data
                    }, ()=>{
                        that.getAllMenuAuth();
                    })
                }
            })
            .catch(function (error) {
                console.log(error);
                Message.error(error.message);
            })
        // }else {
        //     that.getAllMenuAuth(true);
        // }
    };

    /**
     *
     */
    getAllMenuAuth = () => {
        const that = this;
        let roleId = this.state.id ? this.state.id : this.state.systemId;
        axios.get(responsive.responsive.url + '/v1/auth/getAllMenuAuth/'+ this.state.tenantId + "/" + roleId)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    const roleData = [];
                    const datas = data.data;
                    for (let i = 0; i < datas.length; i++) {
                        const d = datas[i];
                        roleData.push({
                            title: d.name,
                            content: that.getMenuList(d),
                        })
                    }
                    that.setState({
                        authList: roleData
                    })
                }
            })
            .catch(function (error) {
                console.log(error);
                Message.error(error.message);
            })
    };

    checkedList =  (id) =>{
        const {roleAuthList} = this.state;
        return roleAuthList.some(
            o=>{
                return o == id;
            }
        )
    };

    /**
     * 获取菜单
     * @param auth
     * @returns {[]}
     */
    getMenuList = (auth) => {
        const d = [];
        if (auth.authVOS) {
            const list = auth.authVOS;
            for (let i = 0; i < list.length; i++) {
                const dd = list[i];
                let oldBtnData = dd.authVOS.map(o => {
                    // 新建
                    if (!this.state.id) {
                        if (this.state.roleAuthList.length > 0 && this.state.roleAuthList.indexOf(o.id) > -1) {
                            return {id: o.id, name: o.name, checked: false};
                        } else {
                            return null;
                        }
                    } else { // 修改
                        return {id: o.id, name: o.name, checked: this.checkedList(o.id)};
                    }
                });
                // 去除空数据
                let newBtnData = [];
                oldBtnData.forEach((v,i) => {
                    if (v != null) {
                        newBtnData.push(v);
                    }
                })
                
                d.push({
                    name: dd.name,
                    btnData: newBtnData
                });
            }
        }

        return d;
    };
    /**
     * 获取区域
     */
    getRoleTenantList = () => {
        const that = this;
        axios.get(responsive.responsive.url + '/v1/tRole/getMyRoleList?tenantId=' + this.state.tenantId)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    let systemId = '';
                    data.data.forEach((o, i) => {
                        if (o.parentId == 2) {
                            systemId = o.id;
                        }
                    });
                    that.setState({
                        // value: data.data,
                        // authList: data.data,
                        systemId: systemId
                    },() => {
                        that.getInstanceRoleByRoleAndTenant();
                    })
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        const tenantId = params.get("tenantId");
        const type = params.get("type") ? params.get("type") : "";
        this.setState({
            id: id,
            tenantId: tenantId,
            type: type
        }, () => {
            this.getRoleTenantList();
            // this.getInstanceRoleByRoleAndTenant();
            if (id) {
                const that = this;
                axios.get(responsive.responsive.url + '/v1/tRole/getRoleById/' + id)
                    .then(function (response) {
                        const {data} = response;
                        if (data.code === 1) {
                            Message.warning(data.message ? data.message : data.data);
                        } else {
                            that.setState({
                                value: data.data
                            })
                        }
                    })
                    .catch(function (error) {
                        Message.error(error.message);
                    })
            }
        });
    };

    /* 表改变
    * @param formValue
    */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };
    /**
     * 表验证
     */
    validateAllFormField = () => {
        form.validateAll((errors, values) => {
            if (errors) {
                Message.warning('请填写必要的数据.');
                return;
            }
            const that = this;
            values["tenantId"] = this.state.tenantId;
            values["roleId"] = this.state.id;
            const authLists = [];
            values.roleData.forEach((o, index)=>{
               o. content.forEach((oo, indexO)=>{
                   oo.btnData.forEach(ooo=>{
                       if (ooo.checked){
                           authLists.push(ooo.id);
                       }
                   })
               })
            });
            values["authLists"] = authLists;
            axios.post(responsive.responsive.url + '/v1/auth/updateRoleAuth', values)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data.name);
                    } else {
                        Message.success("操作成功.");
                        that.props.history.go(-1);
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        });
    };
    /**
     *
     * @param file  {Object} 文件
     * @param value {Array} 值
     */
    onSuccess = (file, value) => {
        const dataList = file.response.data;
        let fileId = dataList[0].fileId;
        this.setState(
            {
                fileId: fileId
            }
        )
    };

    /**
     *
     * @param file  {Object} 出错的文件
     * @param fileList  {Array} 当前值
     */
    onError = (file, fileList) => {
        console.log('Exceed limit', file, fileList);
    };

    /**
     * 表
     * @returns {*}
     */
    render() {
        console.log('this.state=====',this.state);
        const value = {
            name: this.state.value.name,
            roleData: this.state.authList
        };
        return (
            <div>
                <div className='container-header'>
                    {/*<p style={{display: 'inline-block'}}>{"用户权限分配"}</p>*/}
                    <p style={{display: 'inline-block'}}>{this.state.type == 'menu' ? "菜单权限修改" : this.state.id ? "修改角色" : "新建角色"}</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return'
                            style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }}> 返回</a>
                    </Button>
                </div>


                <IceContainer className='container-main'>
                    <IceFormBinderWrapper
                        value={value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formContent}>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span style={{color: '#FF3000'}}>*</span> 角色名称：</div>
                                <IceFormBinder
                                    required
                                    disabled
                                    triggerType="onBlur"
                                    message="请输入角色名称"
                                    name="name"
                                >
                                    <Input
                                        placeholder="请输入角色名称"
                                        disabled={this.state.type == 'menu' ? true : false}
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="name"/>
                                </div>
                            </div>

                            <div className={styles.formItem} style={{display: this.state.id && this.state.type == '' ? 'none' : 'block'}}>
                                <div className={styles.formLabel}>权限选择：</div>

                                <Collapse>
                                    {value.roleData && value.roleData.length > 0 && value.roleData.map((item, index) => {
                                        return (
                                            <Panel title={item.title}>
                                                <Collapse>
                                                    {item.content && item.content.length > 0 && item.content.map((v, i) => {
                                                        return (
                                                            <Panel title={v.name}>
                                                                <Checkbox.Group itemDirection="hoz" defaultValue={this.state.roleAuthList}>
                                                                    {v.btnData && v.btnData.length > 0 && v.btnData.map((btn, j) => {
                                                                        return (
                                                                            <Checkbox
                                                                                value={btn.id}
                                                                                defaultChecked={true}
                                                                                checked={btn.checked}
                                                                                onClick={()=>btn.checked = !btn.checked}> {btn.name} </Checkbox>
                                                                        )
                                                                    })}
                                                                </Checkbox.Group>
                                                            </Panel>
                                                        )
                                                    })}
                                                </Collapse>
                                            </Panel>
                                        )
                                    })}
                                </Collapse>
                            </div>

                            <Button
                                type="primary"
                                className='pipe-btn-submit'
                                onClick={this.validateAllFormField}
                            >
                                提 交
                            </Button>
                        </div>
                    </IceFormBinderWrapper>
                </IceContainer>
            </div>
        );
    }

}

export default AuthorityEditComponents;
